package cn.jhc.social.qq.api.impl.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * QQ API的JSON返回数据中经常会用1表示true，0表示false，Jackson无法直接转换，需要定制下面的BooleanDeserializer来转换。
 * @author luyanfei
 *
 */
public class BooleanDeserializer extends JsonDeserializer<Boolean>{
	@Override
	public Boolean deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		JsonToken token = jp.getCurrentToken();
		if(token == JsonToken.VALUE_STRING) {
			String text = jp.getText().trim();
			if(text.equals("1")) {
				return Boolean.TRUE;
			}
			if(text == null || text.equals("0")) {
				return Boolean.FALSE;
			}
			throw ctxt.weirdStringException(text, Boolean.class, "only \"0\" and \"1\" recongnized.");
		}
		throw ctxt.mappingException(Boolean.class, token);
	}
	
}